/*
 * Project: DianGuanJia
 * 
 * Copyright(c) 2009 www.dianguanjia.cn
 * All rights reserved.
 */
package com.spark.dao;

import java.io.Reader;
import java.nio.charset.Charset;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.spark.core.SparkConfiguration;



public class SessionFactory {
	
	private static final String DEFAULT_CONFIGURATION = "configuration.xml";
	private static SqlSessionFactory sessionFactory;
	
	static {
		try {
			Resources.setCharset(Charset.forName(SparkConfiguration.DEFAULT_ENCODING));
			Reader reader = Resources.getResourceAsReader(DEFAULT_CONFIGURATION);
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
			reader.close();
		} catch (Exception e) {
			throw new RuntimeException("初始化DaoFactory错误. 异常:" + e);
		}
	}

	public static SqlSessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public static SqlSession getSession(boolean autoCommit){
		return getSessionFactory().openSession(autoCommit);
	}
	
	public static SqlSession getSession(){
		return getSession(true);
	}
	
	public static void closeSession(SqlSession session){
		if(session!=null)session.close();
	}

}
